package dk.itu.mobile.util;

import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import dk.itu.mobile.vo.TaskList;

public class XmlSerializer {

	@SuppressWarnings("unchecked") //casting from object to T gives a warning otherwise
	public static <T> T load(String xmlObj, Class<T> type) {
        // create an instance context class, to serialize/deserialize.
        JAXBContext jaxbContext;
        T object = null;
        try {//a tad convoluted way to get type, but if I use the class instead it gives me Java.Object
			jaxbContext = JAXBContext.newInstance(type.newInstance().getClass());
			
			ByteArrayInputStream stream = new ByteArrayInputStream(xmlObj.getBytes());
	        // Create a file input stream for the university Xml.
	       // FileInputStream stream = new FileInputStream(path);
	        // deserialize xml into java objects.
	        object = (T) jaxbContext.createUnmarshaller().unmarshal(stream);

	        return object;
		} catch (JAXBException e) {
			Logger.getLogger(XmlSerializer.class.getName()).log(Level.SEVERE, e.toString());
		} 
        catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} 
		return object;
	}
	
	public static <T> void save(T object, String path) {
		String xmlString = objectToXml(object);
		File file = new File(path);

        // create a bufferedwriter to write Xml
        BufferedWriter output;
		try {
			output = new BufferedWriter(new FileWriter(file));
			output.write(xmlString);
	        output.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	public static <T> String objectToXml(T object) {
        try {
            StringWriter writer = new StringWriter();

            // create a context object for Student Class
            JAXBContext jaxbContext = JAXBContext.newInstance(object.getClass());

            // Call marshal method to serialize student object into Xml
            Marshaller marshaller= jaxbContext.createMarshaller();
            //get the marshaller to format the output with indentation and linebreaks:
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            marshaller.marshal(object, writer);
            

            return writer.toString();

        } catch (JAXBException ex) {
            Logger.getLogger(TaskList.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
	
	
}
